package com.sky.handler;

import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
/*    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result duplicateHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        log.error("username值{}重复输入了"+message.split(" ")[2]);
        return Result.error("数据重复填写,请检查");
    }*/


    //数据重复异常 和全部异常的抓取
    @ExceptionHandler(Exception.class)
    public Result bigHandler(Exception ex){
        ex.printStackTrace();
        if (ex instanceof DuplicateKeyException){
            return Result.error("数据重复填写,请检查");
        }else
            return Result.error("数据错误清联系管理员wangbinghua@itcast.cn");
    }
}
